package com.java.hohenheim.springplatform.web.service.register;

import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.hohenheim.springplatform.data.web.account.RegisterParams;
import com.java.hohenheim.springplatform.db.dao.AccountDAO;
import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.exception.PlatformException;
import com.java.hohenheim.springplatform.redis.ops.RegisterVerificationCodeRedisOps;
import com.java.hohenheim.springplatform.snowflake.SnowflakeWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Hohenheim
 * @date 2020/8/8
 * @description 手机号码注册模块
 */
@Component("phoneRegister")
public class PhoneRegister extends BaseRegister {
    @Autowired
    private AccountDAO mAccountDAO;
    @Autowired
    private RegisterVerificationCodeRedisOps mVerCodeRedis;
    @Resource(name = "UserId")
    private SnowflakeWorker mUserIdWorker;

    @Override
    public boolean register(RegisterParams registerParams) {
        if(!Validator.isMobile(registerParams.getAccount())) {
            throw new PlatformException(ResultCodes.PHONE_FORMAT_ERROR);
        }
        if(StringUtils.isBlank(registerParams.getVerCode())) {
            throw new PlatformException(ResultCodes.VERIFICATION_CODE_MUST_NOT_EMPTY);
        }
        if(StringUtils.isBlank(registerParams.getPwd())) {
            throw new PlatformException(ResultCodes.PWD_MUST_NOT_EMPTY);
        }

        //检查验证码是否正确
        String code = mVerCodeRedis.getVerificationCode(registerParams.getAccount());
        if(!registerParams.getVerCode().equals(code)) {
            throw new PlatformException(ResultCodes.VERIFICATION_CODE_IS_WRONG);
        }

        // 检查该手机号码是否已被注册
        QueryWrapper<AccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", registerParams.getAccount());
        AccountEntity accountEntity = mAccountDAO.getOne(queryWrapper, false);
        if(null != accountEntity) {
            throw new PlatformException(ResultCodes.PHONE_HAS_BEEN_REGISTERED);
        }

        //进行注册
        String pwd = MD5.create().digestHex(registerParams.getPwd());
        AccountEntity entity =new  AccountEntity();
        entity.setUserId(mUserIdWorker.nextId());
        entity.setUserName(registerParams.getAccount());
        entity.setPhone(registerParams.getAccount());
        entity.setPwd(pwd);

        if(!addAccountData(entity)) {
            //注册失败
            throw new PlatformException(ResultCodes.REGISTER_FAIL);
        }

        return true;
    }
}
